/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.commands.queries;

import com.bionic.ce.beans.Query;
import com.bionic.ce.beans.Systemacc;
import com.bionic.ce.beans.User;
import com.bionic.ce.businesslogic.QueryService;
import com.bionic.ce.businesslogic.SystemAccService;
import com.bionic.ce.commands.ICommand;
import com.bionic.ce.commands.systemacc.CommandGoToSystemAccountInfo;
import com.bionic.ce.manager.Config;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MAXIM
 */
public class CommandSelectAndExchengeActiveQuery implements ICommand {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = null;
        try {
            Integer queryId = Integer.parseInt(request.getParameter("queryId"));
            Query query = QueryService.returnCurrentQueryInfo(queryId); 
            Integer openByUser =query.getOpenByUser();
            Double amount = query.getAmount();
            String currencyFrom = query.getCurrencyFrom();
            String currencyTo = query.getCurrencyTo();
            Double rateFrom = query.getRateFrom();
            Integer myUserId=((User)request.getSession().getAttribute("user")).getUserid();
            try {
            Systemacc systemAcc = (Systemacc) (SystemAccService.returnCurrentSystemAccountsInfo(myUserId, currencyFrom).toArray())[0];
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException("You can`t exchange money from "
                        + currencyFrom + " to " + currencyTo + " because you don`t have System account in " + currencyFrom);
            }
            try {
            Systemacc systemAcc = (Systemacc) (SystemAccService.returnCurrentSystemAccountsInfo(myUserId, currencyTo).toArray())[0];
            if (systemAcc.getAmount()<amount*rateFrom)
            throw new IllegalArgumentException("You can`t exchange money from "
                        + currencyFrom + " to " + currencyTo + " because you don`t have enough money in in your " 
                    + currencyTo+" account. To execute this query you should have at least "+amount*rateFrom+" "+currencyTo+" in your account.");   
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException("You can`t exchange money from "
                        + currencyFrom + " to " + currencyTo + " because you don`t have System account in " + currencyTo);
            }
            SystemAccService.executedQueryMoneyTransfer(openByUser, currencyFrom, currencyTo, myUserId, amount, amount*rateFrom);
            query.setStatus("Executed By User");
            query.setClosedRate(rateFrom);
            query.setClosedDate(new Date());
            query.setExecutedByUser(myUserId);
            QueryService.updateCurrentQuery(query);
            request.setAttribute("succesexchange", "Query was exchanged succesfully. "
                    + "From yours system account were withdrawed "+String.format("%.2f", amount*rateFrom)+" "
                    +currencyTo+" and were deposited "+String.format("%.2f", amount)+" "+currencyFrom+".");    
            new CommandGoToSystemAccountInfo().execute(request, response);
            page = Config.getInstance().getProperty(Config.GOTOSYSTEMACCAOUNTSINFO);
        } catch (NumberFormatException e) {
            request.setAttribute("executequeryselecterror", "Please choose query");
            new CommandGoToActiveQueries().execute(request, response);
            page = Config.getInstance().getProperty(Config.GOTOACTIVEQUERIES);
        } catch (IllegalArgumentException e) {
            request.setAttribute("executequeryselecterror", e.getMessage());
            new CommandGoToActiveQueries().execute(request, response);
            page = Config.getInstance().getProperty(Config.GOTOACTIVEQUERIES);
        }

        return page;
    }
}